package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmj.sy.mom.srv.aps.bean.dto.staff.StaffDto;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Group;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.GroupUser;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Span;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseIdReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BasePageResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseSelectItemResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseSelectResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.group.*;
import com.zmj.sy.mom.srv.aps.mapper.GroupMapper;
import com.zmj.sy.mom.srv.aps.mapper.GroupUserMapper;
import com.zmj.sy.mom.srv.aps.mapper.SpanMapper;
import com.zmj.sy.mom.srv.aps.utils.MkBeanUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class GroupService {

    private final GroupMapper groupMapper;

//    private final StationGroupMapper stationGroupMapper;

    private final SpanMapper spanMapper;

    private final GroupUserMapper groupUserMapper;

    @Transactional
    public Integer add(GroupAddReqVo reqVo) {
        Group group = MkBeanUtils.copyProperties(reqVo, Group.class);
        group.setSeq(9999);
        //默认类型为工作组
        group.setType(2);
        if(reqVo.getLineId() == null){
            throw SyExceptionUtils.e("没有所属的产线");
        }
        group.setLineId(reqVo.getLineId());
        groupMapper.insert(group);
        if (!CollectionUtils.isEmpty(reqVo.getStaffList())) {
            //人员不为空
            for (StaffDto staffDto : reqVo.getStaffList()) {
                GroupUser groupUser = new GroupUser();
                groupUser.setUserCode(staffDto.getStaffCode());
                groupUser.setUserName(staffDto.getStaffName());
                groupUser.setGroupId(group.getId());
                groupUserMapper.insert(groupUser);
            }

        }
        return group.getId();
    }

    public BasePageResVo<GroupListResVo> list(GroupListReqVo reqVo) {
        LambdaQueryWrapper<Group> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Group::getType, reqVo.getType());
        wrapper.like(StringUtils.hasText(reqVo.getMyCode()), Group::getMyCode, reqVo.getMyCode());
        wrapper.like(StringUtils.hasText(reqVo.getName()), Group::getName, reqVo.getName());
        wrapper.like(StringUtils.hasText(reqVo.getRemark()), Group::getRemark, reqVo.getRemark());
        wrapper.like(StringUtils.hasText(reqVo.getStartReportWorkVal()), Group::getStartReportWorkVal, reqVo.getStartReportWorkVal());
        wrapper.orderByDesc(Group::getId);
        Page<Group> groupPage = groupMapper.selectPage(reqVo.toPage(), wrapper);
        BasePageResVo<GroupListResVo> resVo = BasePageResVo.of(groupPage, GroupListResVo.class);

        if(resVo.getData().isEmpty()){
            return resVo;
        }
        List<Integer> groupIds = resVo.getData().stream().map(GroupListResVo::getId).collect(Collectors.toList());
        if(reqVo.getType() == 1){
//            QueryWrapper<Employee> empWrapper = Wrappers.query();
//            empWrapper.select("employee_group_id groupId, count(employee_group_id) ct");
//            empWrapper.in("employee_group_id", groupIds);
//            empWrapper.groupBy("employee_group_id");
//            List<Map<String, Object>> maps = employeeMapper.selectMaps(empWrapper);
//
//            Map<Integer, Long> groupIdCountMap = maps.stream().collect(Collectors.toMap(e -> (Integer) e.get("groupId"), e -> (Long) e.get("ct")));
//            for (GroupListResVo datum : resVo.getData()) {
//                Long i = groupIdCountMap.get(datum.getId());
//                if(i == null){
//                   i = 0L;
//                }
//                datum.setCount(i.intValue());
//            }

        } else if(reqVo.getType() == 2){

            List<Span> selectList = spanMapper.selectList(Wrappers.query());
            Map<Integer, Span> spanIdMap = selectList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));


            for (GroupListResVo datum : resVo.getData()) {
                datum.setMasterCount(0);
                datum.setSlaveCount(0);

                if(datum.getSpanId() != null){
                    Span span = spanIdMap.get(datum.getSpanId());
                    if(span != null){
                        datum.setSpanName(span.getName());
                    }
                }
            }

        }

        return resVo;
    }

    public GroupGetResVo get(BaseIdReqVo reqVo) {
        Group group = groupMapper.selectById(reqVo.getId());
        return MkBeanUtils.copyProperties(group, GroupGetResVo.class);
    }

    @Transactional
    public void edit(GroupAddReqVo reqVo) {
        LambdaQueryWrapper<Group> groupWrapper = new LambdaQueryWrapper<>();
        groupWrapper.eq(Group::getDeleted, 0);
        groupWrapper.eq(Group::getId, reqVo.getId());
//        groupWrapper.eq(Group::getMyCode, reqVo.getMyCode());
        Group group = groupMapper.selectOne(groupWrapper);
        MkBeanUtils.copyPropertiesIgnore(reqVo, group);
        if (Objects.isNull(reqVo.getTeamId())) {
            group.setTeamId(null);
        }
        groupMapper.updateById(group);

        try {
            LambdaQueryWrapper<GroupUser> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(GroupUser::getGroupId, group.getId());
            groupUserMapper.delete(wrapper);
            if (CollUtil.isNotEmpty(reqVo.getStaffList())) {
                //人员不为空
                for(StaffDto staffDto : reqVo.getStaffList()){
                    GroupUser groupUser = new GroupUser();
                    groupUser.setUserCode(staffDto.getStaffCode());
                    groupUser.setUserName(staffDto.getStaffName());
                    groupUser.setGroupId(group.getId());
                    groupUserMapper.insert(groupUser);

                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Transactional
    public void delete(BaseIdReqVo reqVo) {
        LambdaQueryWrapper<Group> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Group::getId, reqVo.getId());
        Group group = groupMapper.selectOne(queryWrapper);
        //删除GroupUser表数据
        LambdaQueryWrapper<GroupUser> deleteQw = new LambdaQueryWrapper<>();
        deleteQw.eq(GroupUser::getDeleted,0);
        deleteQw.eq(GroupUser::getGroupId, group.getId());
        groupUserMapper.delete(deleteQw);

        //删除Group表数据
        groupMapper.deleteById(reqVo.getId());

//        Integer stationCt = stationGroupMapper.selectCount(Wrappers.<StationGroup>lambdaQuery().eq(StationGroup::getGroupId, reqVo.getId()));
//        if(stationCt > 0){
//            throw SyExceptionUtils.e("该组已被工位使用，无法删除");
//        }

//        Integer employeeCt = employeeMapper.selectCount(Wrappers.<Employee>lambdaQuery().eq(Employee::getEmployeeGroupId, reqVo.getId()));
//        if(employeeCt > 0){
//            throw SyExceptionUtils.e("该组已被员工使用，无法删除");
//        }
    }

    public BaseSelectResVo select(GroupSelectReqVo reqVo) {
        LambdaQueryWrapper<Group> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(reqVo.getType() != null, Group::getType, reqVo.getType());
        wrapper.orderByDesc(Group::getId);

        List<Group> groups = groupMapper.selectList(wrapper);
        List<BaseSelectItemResVo> collect = groups.stream()
                .sorted(Comparator.comparing(Group::getSeq))
                .map(e -> new BaseSelectItemResVo(e.getName(), e.getId(), "my_code", e.getMyCode()))
                .collect(Collectors.toList());

        return BaseSelectResVo.of(collect);
    }

    public BaseSelectResVo selectPhase(GroupSelectReqVo reqVo) {
        List<Group> groups = groupMapper.selectPhaseList();
        List<BaseSelectItemResVo> collect = groups.stream()
                .sorted(Comparator.comparing(Group::getSeq))
                .map(e -> new BaseSelectItemResVo(e.getName(), e.getId(), "my_code", e.getMyCode()))
                .collect(Collectors.toList());

        return BaseSelectResVo.of(collect);
    }
}
